package com.jichangxiu.common.utils;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class EncodeUtils {

    private static final char[] BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();

    public static String encodeHex(byte[] input) {
        return new String(Hex.encodeHex(input));
    }

    public static byte[] decodeHex(String input) {
        try {
            return Hex.decodeHex(input.toCharArray());
        } catch (DecoderException ex) {
            throw new RuntimeException("【EncodeUtils】【Hex】解码失败", ex);
        }
    }

    public static String encodeBase64(byte[] input) {
        return new String(Base64.encodeBase64(input));
    }

    public static String encodeBase64(String input) {
        return new String(Base64.encodeBase64(input.getBytes(StandardCharsets.UTF_8)));
    }

    public static byte[] decodeBase64(String input) {
        return Base64.decodeBase64(input.getBytes());
    }

    public static String decodeBase64Str(String input) {
        return new String(Base64.decodeBase64(input.getBytes()), StandardCharsets.UTF_8);
    }

    public static String encodeBase62(byte[] input) {
        char[] chars = new char[input.length];
        for (int i = 0; i < input.length; i++)
            chars[i] = BASE62[((input[i] & 0xFF) % BASE62.length)];
        return new String(chars);
    }

    public static String encodeUrl(String part) {
        try {
            return URLEncoder.encode(part, String.valueOf(StandardCharsets.UTF_8));
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException("【EncodeUtils】【URL】编码异常", ex);
        }
    }

    public static String decodeUrl(String part) {
        try {
            return URLDecoder.decode(part, String.valueOf(StandardCharsets.UTF_8));
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException("【EncodeUtils】【URL】解码异常", ex);
        }
    }

    public static String bcEncode(String str) {
        return new BCryptPasswordEncoder().encode(str);
    }

    public static Boolean bcCompare(String password, String encodePassword) {
        return new BCryptPasswordEncoder().matches(password, encodePassword);
    }

}
